Skip to content

PygmentsHighlighter

Base classes

Name Children Inherits
SyntaxHighlighter
prettyqt.gui.syntaxhighlighter

⋔ Inheritance diagram

graph TD
  3398420805["syntaxhighlighters.PygmentsHighlighter"]
  1397204487["gui.SyntaxHighlighter"]
  1524332846["gui.SyntaxHighlighterMixin"]
  3227531497["core.ObjectMixin"]
  2751680898["builtins.object"]
  1270797816["QtGui.QSyntaxHighlighter"]
  3984060476["QtCore.QObject"]
  37984305["Shiboken.Object"]
  1397204487 --> 3398420805
  1524332846 --> 1397204487
  3227531497 --> 1524332846
  2751680898 --> 3227531497
  2751680898 --> 1524332846
  1270797816 --> 1397204487
  3984060476 --> 1270797816
  37984305 --> 3984060476
  2751680898 --> 37984305

🛈 DocStrings

Bases: SyntaxHighlighter

Syntax highlighter that uses Pygments for parsing.

Source code in prettyqt/syntaxhighlighters/pygmentshighlighter.py
class PygmentsHighlighter(gui.SyntaxHighlighter):
    """Syntax highlighter that uses Pygments for parsing."""

    # ---------------------------------------------------------------------------
    #  "QSyntaxHighlighter" interface
    # ---------------------------------------------------------------------------

    def __init__(
        self,
        parent: gui.QTextDocument,
        lexer: str,
        style: StyleStr | None = None,
    ):
        super().__init__(parent)
        self._document = gui.QTextDocument(self)
        self._formatter = html.HtmlFormatter(nowrap=True)
        self._style = None
        self._stylename = ""
        if style is None:
            gui.GuiApplication.styleHints().colorSchemeChanged.connect(
                self.adjust_style_to_palette
            )
        self.set_style(style)
        if lexer == "regex":
            self._lexer = lexers.load_lexer_from_file(str(paths.RE_LEXER_PATH))
        else:
            self._lexer = lexers.get_lexer_by_name(lexer)

    def __repr__(self):
        return get_repr(self, lexer=self._lexer.aliases[0])

    def highlightBlock(self, string):
        """Highlight a block of text."""
        if (
            isinstance(self._lexer, lexer.RegexLexer)
            and type(self._lexer).get_tokens_unprocessed
            is lexer.RegexLexer.get_tokens_unprocessed
        ):
            prev_data = self.currentBlock().previous().userData()
            prev_stack = getattr(prev_data, "syntax_stack", None)
            statestack = list(prev_stack) if isinstance(prev_stack, list) else ["root"]
            text = self._lexer._preprocess_lexer_input(string)
            tokens: Iterable[tuple[Any, str]] = (
                (tok, val)
                for _, tok, val in _get_tokens_unprocessed(self._lexer, text, statestack)
            )
            if self._lexer.filters:
                tokens = pygments_filter.apply_filters(
                    tokens, self._lexer.filters, self._lexer
                )
            index = 0
            for token, chunk in tokens:
                length = qstring_length(chunk)
                self.setFormat(index, length, self._get_format(token))
                index += length
            data = gui.TextBlockUserData(syntax_stack=statestack)
            self.currentBlock().setUserData(data)
        else:
            index = 0
            for token, chunk in self._lexer.get_tokens(string):
                length = qstring_length(chunk)
                self.setFormat(index, length, self._get_format(token))
                index += length

    # ---------------------------------------------------------------------------
    # "PygmentsHighlighter" interface
    # ---------------------------------------------------------------------------

    def set_style(self, style: StyleStr | None):
        match style:
            case None:
                self.adjust_style_to_palette()
                return
            case str():
                self._style = styles.get_style_by_name(style)
                self._stylename = style
            case _:
                raise TypeError(style)
        self._clear_caches()

    def get_style(self) -> StyleStr | str:
        return self._stylename

    def adjust_style_to_palette(self):
        pal = gui.GuiApplication.get_palette()
        style = "monokai" if pal.is_dark() else "default"
        self.set_style(style)

    def set_style_sheet(self, stylesheet: str):
        """Sets a CSS stylesheet.

        The classes in the stylesheet should correspond to those generated by:

            pygmentize -S <style> -f html

        Note that "set_style" and "set_style_sheet" completely override each
        other, i.e. they cannot be used in conjunction.
        """
        self._document.setDefaultStyleSheet(stylesheet)
        self._style = None
        self._clear_caches()

    # ---------------------------------------------------------------------------
    # Protected interface
    # ---------------------------------------------------------------------------

    def _clear_caches(self):
        """Clear caches for brushes and formats."""
        _get_brush.cache_clear()
        self._get_format.cache_clear()

    @functools.cache  # noqa: B019
    def _get_format(self, token: str) -> gui.QTextCharFormat:
        """Returns a QTextCharFormat for token or None."""
        if self._style is None:
            return self._get_format_from_document(token, self._document)
        return _get_format_from_style(token, self._style)

    def _get_format_from_document(
        self, token: str, document: gui.QTextDocument
    ) -> gui.QTextCharFormat:
        """Return a QTextCharFormat for token from document."""
        _, html = next(self._formatter._format_lines([(token, "dummy")]))
        document.setHtml(html)
        return gui.TextCursor(document).charFormat()

    style = core.Property(
        str,
        get_style,
        set_style,
        doc="Pygments style for the highlighter",
    )

highlightBlock(string)

Highlight a block of text.

Source code in prettyqt/syntaxhighlighters/pygmentshighlighter.py
def highlightBlock(self, string):
    """Highlight a block of text."""
    if (
        isinstance(self._lexer, lexer.RegexLexer)
        and type(self._lexer).get_tokens_unprocessed
        is lexer.RegexLexer.get_tokens_unprocessed
    ):
        prev_data = self.currentBlock().previous().userData()
        prev_stack = getattr(prev_data, "syntax_stack", None)
        statestack = list(prev_stack) if isinstance(prev_stack, list) else ["root"]
        text = self._lexer._preprocess_lexer_input(string)
        tokens: Iterable[tuple[Any, str]] = (
            (tok, val)
            for _, tok, val in _get_tokens_unprocessed(self._lexer, text, statestack)
        )
        if self._lexer.filters:
            tokens = pygments_filter.apply_filters(
                tokens, self._lexer.filters, self._lexer
            )
        index = 0
        for token, chunk in tokens:
            length = qstring_length(chunk)
            self.setFormat(index, length, self._get_format(token))
            index += length
        data = gui.TextBlockUserData(syntax_stack=statestack)
        self.currentBlock().setUserData(data)
    else:
        index = 0
        for token, chunk in self._lexer.get_tokens(string):
            length = qstring_length(chunk)
            self.setFormat(index, length, self._get_format(token))
            index += length

set_style_sheet(stylesheet: str)

Sets a CSS stylesheet.

The classes in the stylesheet should correspond to those generated by:

pygmentize -S <style> -f html

Note that "set_style" and "set_style_sheet" completely override each other, i.e. they cannot be used in conjunction.

Source code in prettyqt/syntaxhighlighters/pygmentshighlighter.py
def set_style_sheet(self, stylesheet: str):
    """Sets a CSS stylesheet.

    The classes in the stylesheet should correspond to those generated by:

        pygmentize -S <style> -f html

    Note that "set_style" and "set_style_sheet" completely override each
    other, i.e. they cannot be used in conjunction.
    """
    self._document.setDefaultStyleSheet(stylesheet)
    self._style = None
    self._clear_caches()

:fa-brands-github: Show source on GitHub